<template>
  <!-- Instructions Stage -->
  <div v-if="stage === 'instructions'" class="max-w-2xl mx-auto">
    <transition appear name="fade">
      <Card class="bg-white/90 backdrop-blur-sm border-purple-200 shadow-lg">
        <CardHeader class="text-center pb-8">
          <div
            class="w-16 h-16 bg-gradient-to-br from-purple-600 to-pink-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
          >
            <Lightbulb class="w-8 h-8 text-white" />
          </div>
          <CardTitle class="text-2xl text-slate-800">{{
            t("creativeThinkingTest.testTitle")
          }}</CardTitle>
          <p class="text-slate-600 mt-2">
            {{ t("creativeThinkingTest.testDescription") }}
          </p>
        </CardHeader>
        <CardContent class="space-y-6">
          <div
            class="bg-gradient-to-r from-purple-50 to-pink-50 rounded-xl p-6 border border-purple-100"
          >
            <h3
              class="font-semibold text-purple-900 mb-4 flex items-center gap-2"
            >
              <Star class="w-5 h-5" />
              {{ t("creativeThinkingTest.instructionsTitle") }}
            </h3>
            <div class="space-y-3 text-slate-700">
              <div class="flex gap-3">
                <span class="step-number">1</span>
                <p>{{ t("creativeThinkingTest.instruction1") }}</p>
              </div>
              <div class="flex gap-3">
                <span class="step-number">2</span>
                <p>{{ t("creativeThinkingTest.instruction2") }}</p>
              </div>
              <div class="flex gap-3">
                <span class="step-number">3</span>
                <p>{{ t("creativeThinkingTest.instruction3") }}</p>
              </div>
              <div class="flex gap-3">
                <span class="step-number">4</span>
                <p>{{ t("creativeThinkingTest.instruction4") }}</p>
              </div>
            </div>
          </div>
          <div class="grid md:grid-cols-2 gap-4">
            <div
              class="task-preview-box border-blue-200 from-blue-50 to-blue-100"
            >
              <h4
                class="font-semibold text-blue-800 mb-2 flex items-center gap-2"
              >
                <Brain class="w-4 h-4" />
                {{ t("creativeThinkingTest.divergentThinking") }}
              </h4>
              <p class="text-sm text-blue-700">
                {{ t("creativeThinkingTest.divergentThinkingDescription") }}
              </p>
            </div>
            <div
              class="task-preview-box border-green-200 from-green-50 to-green-100"
            >
              <h4
                class="font-semibold text-green-800 mb-2 flex items-center gap-2"
              >
                <Palette class="w-4 h-4" />
                {{ t("creativeThinkingTest.creativeExpression") }}
              </h4>
              <p class="text-sm text-green-700">
                {{ t("creativeThinkingTest.creativeExpressionDescription") }}
              </p>
            </div>
          </div>
          <div
            class="bg-gradient-to-r from-amber-50 to-orange-50 rounded-xl p-4 border border-amber-200"
          >
            <h4
              class="font-semibold text-amber-800 mb-2 flex items-center gap-2"
            >
              <Sparkles class="w-4 h-4" />
              {{ t("creativeThinkingTest.scoringCriteriaTitle") }}
            </h4>
            <div class="text-sm text-amber-700 space-y-1">
              <p>
                <strong>{{ t("creativeThinkingTest.creativity") }}</strong>
              </p>
              <p>
                <strong>{{ t("creativeThinkingTest.originality") }}</strong>
              </p>
              <p>
                <strong>{{ t("creativeThinkingTest.relevance") }}</strong>
              </p>
            </div>
          </div>
          <Button
            class="w-full bg-gradient-to-r from-purple-600 to-pink-500 hover:from-purple-700 hover:to-pink-600 text-white py-3 text-lg font-semibold shadow-lg"
            size="lg"
            @click="handleStartTest"
          >
            {{ t("creativeThinkingTest.startCreativeJourney") }}
          </Button>
        </CardContent>
      </Card>
    </transition>
  </div>

  <!-- Test Stage -->
  <div
    v-else-if="stage === 'test' && currentQuestionData"
    class="max-w-4xl mx-auto space-y-6"
  >
    <div class="flex flex-col sm:flex-row gap-4 items-center justify-between">
      <div class="flex items-center gap-4 flex-wrap">
        <Badge
          class="bg-purple-100 text-purple-700 border-purple-300"
          variant="outline"
          >{{ t("creativeThinkingTest.question") }} {{ currentQuestion + 1 }} /
          {{ QUESTIONS_PER_TEST }}
        </Badge>
        <Badge :class="difficultyClass" variant="outline">{{
          difficultyText
        }}</Badge>
        <Badge
          class="bg-pink-100 text-pink-700 border-pink-300"
          variant="outline"
          >{{ currentQuestionData.category }}
        </Badge>
      </div>
      <div class="flex items-center gap-2">
        <Clock class="w-4 h-4 text-slate-500" />
        <span
          :class="[
            'font-mono text-lg font-bold',
            timeLeft <= 30 ? 'text-red-500' : 'text-slate-700',
          ]"
        >
          {{ Math.floor(timeLeft / 60) }}:{{
            (timeLeft % 60).toString().padStart(2, "0")
          }}
        </span>
      </div>
    </div>

    <Progress
      :model-value="(currentQuestion / QUESTIONS_PER_TEST) * 100"
      class="h-2"
    />

    <Card class="bg-white/90 backdrop-blur-sm border-purple-200 shadow-lg">
      <CardHeader>
        <CardTitle class="text-xl text-slate-800 leading-relaxed">{{
          currentQuestionData.prompt
        }}</CardTitle>
        <div
          v-if="currentQuestionData.evaluationCriteria.length > 0"
          class="flex flex-wrap gap-2 mt-3"
        >
          <span class="text-sm text-slate-600">{{
            t("creativeThinkingTest.scoringFocusLabel")
          }}</span>
          <Badge
            v-for="(criteria, index) in currentQuestionData.evaluationCriteria"
            :key="index"
            class="text-xs"
            variant="secondary"
            >{{ criteria }}
          </Badge>
        </div>
      </CardHeader>
      <CardContent class="space-y-6">
        <div class="space-y-4">
          <Textarea
            :value="currentResponse"
            @input="currentResponse = $event.target.value"
            placeholder="在这里发挥您的创意想象..."
            class="min-h-[200px] text-base leading-relaxed resize-none border-purple-200 focus:border-purple-400"
            :disabled="showTransition"
          />

          <div class="flex justify-between items-center text-sm text-slate-600">
            <span
              >{{ t("creativeThinkingTest.wordCount") }} {{ wordCount }}</span
            >
            <span
              >{{ t("creativeThinkingTest.suggestion") }}
              {{ suggestionText }}</span
            >
          </div>
        </div>
        <Button
          :disabled="currentResponse.trim().length < 10 || showTransition"
          class="w-full bg-gradient-to-r from-purple-600 to-pink-500 hover:from-purple-700 hover:to-pink-600 text-white py-3 text-lg font-semibold shadow-lg"
          size="lg"
          @click="handleSubmit"
        >
          {{
            showTransition
              ? t("creativeThinkingTest.evaluating")
              : t("creativeThinkingTest.submitIdea")
          }}
        </Button>
      </CardContent>
    </Card>

    <transition name="fade">
      <div
        v-if="showTransition"
        class="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center"
      >
        <Card
          class="bg-gradient-to-br from-purple-500 to-pink-500 text-white max-w-md mx-4"
        >
          <CardContent class="p-8 text-center">
            <div class="w-16 h-16 mx-auto mb-4 animate-spin-slow">
              <Lightbulb class="w-full h-full" />
            </div>
            <h3 class="text-xl font-semibold mb-2">
              {{ t("creativeThinkingTest.evaluatingCreative") }}
            </h3>
            <p class="text-purple-100">
              {{ t("creativeThinkingTest.analyzingInnovation") }}
            </p>
          </CardContent>
        </Card>
      </div>
    </transition>
  </div>

  <!-- Results Stage -->
  <div v-else-if="stage === 'results'" class="max-w-2xl mx-auto">
    <transition appear name="fade">
      <Card class="bg-white/90 backdrop-blur-sm border-purple-200 shadow-xl">
        <CardHeader class="text-center pb-6">
          <div
            class="w-20 h-20 bg-gradient-to-br from-purple-600 to-pink-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
          >
            <Trophy class="w-10 h-10 text-white" />
          </div>
          <CardTitle class="text-3xl text-slate-800 mb-2">{{
            t("creativeThinkingTest.testComplete")
          }}</CardTitle>
          <div
            class="text-6xl font-bold bg-gradient-to-r from-purple-600 to-pink-500 bg-clip-text text-transparent"
          >
            {{ results.finalScore }}
          </div>
          <p class="text-slate-600">
            {{ t("creativeThinkingTest.creativeThinkingScore") }}
          </p>
        </CardHeader>
        <CardContent class="space-y-6">
          <div class="grid grid-cols-3 gap-4">
            <div
              class="info-box from-purple-50 to-purple-100 border-purple-200"
            >
              <div class="info-box-title text-purple-600">
                {{ results.averageCreativity }}
              </div>
              <div class="info-box-body">
                {{ t("creativeThinkingTest.creativityScore") }}
              </div>
            </div>
            <div class="info-box from-pink-50 to-pink-100 border-pink-200">
              <div class="info-box-title text-pink-600">
                {{ results.averageOriginality }}
              </div>
              <div class="info-box-body">
                {{ t("creativeThinkingTest.originalityScore") }}
              </div>
            </div>
            <div
              class="info-box from-indigo-50 to-indigo-100 border-indigo-200"
            >
              <div class="info-box-title text-indigo-600">
                {{ results.totalWordCount }}
              </div>
              <div class="info-box-body">
                {{ t("creativeThinkingTest.totalWordCount") }}
              </div>
            </div>
          </div>
          <Button
            class="w-full bg-gradient-to-r from-purple-600 to-pink-500 hover:from-purple-700 hover:to-pink-600 text-white py-3 text-lg font-semibold shadow-lg"
            size="lg"
            @click="handleComplete"
          >
            {{ t("creativeThinkingTest.viewDetails") }}
          </Button>
        </CardContent>
      </Card>
    </transition>
  </div>
</template>

<script setup>
import { ref, computed, watch, onUnmounted } from "vue";
import { useI18n } from "vue-i18n";
import {
  Lightbulb,
  Clock,
  Trophy,
  Star,
  Sparkles,
  Brain,
  Palette,
} from "lucide-vue-next";
import { getCREATIVE_THINKING_POOL } from "../constants/creativeThinking";

const emit = defineEmits(["complete"]);

const { t, locale } = useI18n();

const CREATIVE_THINKING_POOL = getCREATIVE_THINKING_POOL(locale.value);
console.log("object", CREATIVE_THINKING_POOL, locale.value);
// --- Constants ---
const QUESTIONS_PER_TEST = 8;
const TYPE_DISPLAY_NAMES = {
  divergent_thinking: "发散思维",
  problem_solving: "问题解决",
  story_creation: "故事创作",
  conceptual_combination: "概念融合",
  alternative_uses: "替代用途",
  hypothetical_scenarios: "假设情境",
  improvement_ideas: "改进构想",
  metaphorical_thinking: "比喻思维",
  design_challenge: "设计挑战",
  future_prediction: "未来预测",
  creative_naming: "创意命名",
  reverse_thinking: "逆向思维",
  invention_ideas: "发明创想",
  social_innovation: "社会创新",
  artistic_expression: "艺术表达",
  environmental_solutions: "环保方案",
  technology_application: "技术应用",
  cultural_fusion: "文化融合",
  educational_innovation: "教育创新",
  business_model: "商业模式",
};

// --- State ---
const stage = ref("instructions");
const currentQuestion = ref(0);
const selectedQuestions = ref([]);
const responses = ref([]);
const currentResponse = ref("");
const timeLeft = ref(0);
const startTime = ref(0);
const score = ref(0);
const showTransition = ref(false);

let timer = null;

// --- Computed Properties ---
const currentQuestionData = computed(
  () => selectedQuestions.value[currentQuestion.value]
);
const wordCount = computed(
  () => currentResponse.value.trim().split(/\s+/).filter(Boolean).length
);
const difficultyClass = computed(() => {
  if (!currentQuestionData.value) return "";
  switch (currentQuestionData.value.difficulty) {
    case "easy":
      return "bg-green-100 text-green-700 border-green-300";
    case "medium":
      return "bg-yellow-100 text-yellow-700 border-yellow-300";
    case "hard":
      return "bg-red-100 text-red-700 border-red-300";
    default:
      return "";
  }
});
const difficultyText = computed(() => {
  if (!currentQuestionData.value) return "";
  switch (currentQuestionData.value.difficulty) {
    case "easy":
      return t("creativeThinkingTest.difficultyEasy");
    case "medium":
      return t("creativeThinkingTest.difficultyMedium");
    case "hard":
      return t("creativeThinkingTest.difficultyHard");
    default:
      return "";
  }
});
const suggestionText = computed(() => {
  if (!currentQuestionData.value) return "";
  return currentQuestionData.value.expectedCount > 1
    ? `${currentQuestionData.value.expectedCount}${t(
        "creativeThinkingTest.ideas"
      )}`
    : `100${t("creativeThinkingTest.wordsAbove")}`;
});
const results = computed(() => {
  if (stage.value !== "results") return {};
  const totalQuestions = selectedQuestions.value.length;
  if (totalQuestions === 0)
    return {
      finalScore: 0,
      averageCreativity: 0,
      averageOriginality: 0,
      totalWordCount: 0,
    };
  const averageScore = score.value / totalQuestions;
  const finalScore = Math.round((averageScore / 5) * 100);
  const averageCreativity =
    Math.round(
      (responses.value.reduce((sum, r) => sum + r.creativity, 0) /
        responses.value.length) *
        10
    ) / 10;
  const averageOriginality =
    Math.round(
      (responses.value.reduce((sum, r) => sum + r.originality, 0) /
        responses.value.length) *
        10
    ) / 10;
  const totalWordCount = responses.value.reduce(
    (sum, r) => sum + r.wordCount,
    0
  );
  return { finalScore, averageCreativity, averageOriginality, totalWordCount };
});

// --- Methods ---
const selectRandomQuestions = () => {
  const shuffled = [...CREATIVE_THINKING_POOL].sort(() => 0.5 - Math.random());
  const questionsByType = {};
  shuffled.forEach((q) => {
    if (!questionsByType[q.type]) questionsByType[q.type] = [];
    if (questionsByType[q.type].length < 1) questionsByType[q.type].push(q);
  });
  const selected = Object.values(questionsByType).flat();
  if (selected.length < QUESTIONS_PER_TEST) {
    const remaining = shuffled.filter(
      (q) => !selected.some((s) => s.id === q.id)
    );
    selected.push(...remaining.slice(0, QUESTIONS_PER_TEST - selected.length));
  }
  return selected.sort(() => 0.5 - Math.random()).slice(0, QUESTIONS_PER_TEST);
};

const evaluateResponse = (response, question) => {
  const wordCount = response.trim().split(/\s+/).filter(Boolean).length;
  let creativity = 3,
    originality = 3,
    relevance = 3;
  if (wordCount > 100) creativity += 0.5;
  if (wordCount > 200) creativity += 0.5;
  const uncommonWords = ["创新", "独特", "革命", "突破", "前所未有", "想象"];
  originality +=
    uncommonWords.filter((word) => response.includes(word)).length * 0.3;
  if (
    question.type === "divergent_thinking" &&
    response.includes(t("creativeThinkingTest.useWord"))
  )
    relevance += 0.5;
  if (question.type === "problem_solving" && response.includes("解决"))
    relevance += 0.5;
  if (question.type === "story_creation" && wordCount > 50) relevance += 1;
  return {
    content: response,
    wordCount,
    submittedAt: Date.now(),
    creativity: Math.min(5, Math.max(1, creativity)),
    originality: Math.min(5, Math.max(1, originality)),
    relevance: Math.min(5, Math.max(1, relevance)),
  };
};

const handleStartTest = () => {
  selectedQuestions.value = selectRandomQuestions();
  stage.value = "test";
  startTime.value = Date.now();
};

const handleSubmit = () => {
  if (!currentQuestionData.value) return;
  const evaluatedResponse = evaluateResponse(
    currentResponse.value,
    currentQuestionData.value
  );
  responses.value.push(evaluatedResponse);
  const questionScore =
    (evaluatedResponse.creativity +
      evaluatedResponse.originality +
      evaluatedResponse.relevance) /
    3;
  score.value += questionScore;
  currentResponse.value = "";
  showTransition.value = true;
  setTimeout(() => {
    showTransition.value = false;
    if (currentQuestion.value < selectedQuestions.value.length - 1) {
      currentQuestion.value++;
    } else {
      stage.value = "results";
    }
  }, 2000);
};

const handleComplete = () => {
  const res = results.value;
  emit("complete", {
    id: Date.now().toString(),
    testType: "creative-thinking",
    score: res.finalScore,
    completedAt: new Date(),
    duration: Math.round((Date.now() - startTime.value) / 1000),
    details: { ...res, totalQuestions: selectedQuestions.value.length },
  });
};

// --- Lifecycle Hooks ---
watch(stage, (newStage) => {
  if (newStage !== "test") {
    if (timer) clearInterval(timer);
  }
});

watch(
  currentQuestion,
  (newQ, oldQ) => {
    if (stage.value === "test" && selectedQuestions.value.length > 0) {
      const question = selectedQuestions.value[newQ];
      timeLeft.value = question.timeLimit;
    }
  },
  { immediate: true }
);

onMounted(() => {
  timer = setInterval(() => {
    if (stage.value === "test" && timeLeft.value > 0) {
      timeLeft.value--;
      if (timeLeft.value <= 0) {
        handleSubmit();
      }
    }
  }, 1000);
});

onUnmounted(() => {
  if (timer) clearInterval(timer);
});
</script>

<style scoped>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.step-number {
  @apply w-6 h-6 bg-purple-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5;
}

.task-preview-box {
  @apply bg-gradient-to-br rounded-xl p-4 border;
}

.info-box {
  @apply text-center p-4 bg-gradient-to-br rounded-xl border;
}

.info-box-title {
  @apply text-2xl font-bold mb-1;
}

.info-box-body {
  @apply text-sm;
}

.result-row {
  @apply flex justify-between items-center p-3 bg-slate-50 rounded-lg;
}

.animate-spin-slow {
  animation: spin 2s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
